package com.example.shiro;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author: lex
 * @Date: 2018/10/14
 */
public class ShiroFilterUtil {

    public static Map<String, String> getFilterChainDefinitionMap() {
        Connection ct = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Map<String, String> filterMap = new LinkedHashMap<>();
        try {
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //得到连接
            ct = DriverManager.getConnection("jdbc:mysql://localhost:3306/shiro", "root", "LinEnXi123!");
            //创建一个PreparedStatement，用于向数据库放松sql语句
            ps = ct.prepareStatement("select * from tb_shiro_filter order by rank and is_delete=0");
            //得到结果
            rs = ps.executeQuery();//这个方法适用于从表中查找数据
            //如果要向表中插入，删除，更新数据需要使用方法executeUpdate();
            while (rs.next()) {//这里rs.next()一定要使用next()方法，否则有空指针错误
                String pages = rs.getString("pages");
                String filters = rs.getString("perms");
                filterMap.put(pages, filters);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源,记住关闭资源的顺序,根据得到赋值的反顺序进行关闭资源
            try {
                if (rs != null) {
                    rs.close();
                }
                if (ps != null)
                    ps.close();
                if (ct != null)
                    ct.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return filterMap;
    }
}
